import axios from 'axios'
import {Message } from 'element-ui'
import store from '@/store'
import { getToken ,removeToken} from '@/utils/auth'
import qs from "qs";
import {Base64} from 'js-base64';
import website from "@/config/website";
import util from "@/utils/util";
const status = {
    ok: [200],
    error:[500,404],
    noAuth: 401
}

const http = axios.create({
    timeout: 50000 ,// 请求超时事间单位毫秒
    baseURL: '/api'
})

// 请求拦截器
http.interceptors.request.use(config => {

        if (getToken()) {
            config.headers['authorization'] = getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
        }
        config.meta = config.meta || {}
        if(["POST","post"].includes(config.method)  && config.meta.from === true){
            let data =  config.params || config.data ;
            delete config.params ;
            config.data = qs.stringify(data)
        }else if(util.isEmpty(config.method)|| ["GET","get"].includes(config.method)){
            let data =  config.params || config.data ;
            delete config.data ;
            config.params = data ;
        }
        return config
    },
    error => {
        console.error(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
http.interceptors.response.use(
    response => {//成功
        let res = response.data ;
        if(status.noAuth === res.code){
            removeToken();
            location.replace("/login")
        }
        return res;
    },
    error => {//失败
        let msg = error
        let resp = {
            status: false ,
            msg: msg,
            code: 500
        }
        Message({
            message: msg,
            type: 'error',
            duration: 5 * 1000
        })
        return resp
    }
)
http.download = function(url,params){
   return this.post(url ,params, {
       responseType: "blob", // 设置响应类型为二进制数据
    })
}
export default http
